package com.productAndConsume;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//lock接口 实现线程通信
//循环等待会产生死锁
//Lock 替代了 synchronized 方法和语句的使用，Condition 替代了 Object 监视器方法的使用。
public class TestLockPC {
    public static void main(String[] args) throws InterruptedException {
        Data2 data =new Data2();

        Thread p2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "p2");
        Thread c1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "c1");
        Thread p1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "p1");
        Thread c2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "c2");
//        p2.start();
//        p1.start();
//        c1.start();
//        c2.start();
        while (true){
            System.out.println( TimeUnit.DAYS.toHours( 1 ) );
            TimeUnit.SECONDS.sleep(5);
            break;
        }


    }
}
class Data2{
    private int number=0;
    Lock lock=new ReentrantLock();
    Condition condition=lock.newCondition();//绑定一个lock实例 等价 Object 监视器方法
    //+1
    public void increment() throws InterruptedException{
        lock.lock();
        try {
            //业务代码
            while(number!=0){
                //等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            condition.signalAll();		//通知
        } catch (Exception e) {
            // TODO: handle exception
        }finally{
            lock.unlock();
        }
    }
    //-1
    public void decrement() throws InterruptedException{
        lock.lock();
        try {

            //业务代码
            while(number!=1){
                //等待
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            condition.signalAll();		//通知
        } catch (Exception e) {
            // TODO: handle exception
        }finally{
            lock.unlock();
        }
    }

}